<?php
$con = mysqli_connect('localhost', 'root', 'root', 'project-manage');

$sql = 'select a.* from (
	select a.id,a.total_step, a.audit_step,a.audit_id, count(1) node_count from ba_wf_workflow a 
	left join ba_wf_node_record b on a.id = b.flow_id
	where b.record_type = 2 and a.audit_step < 5
	group by a.id,a.audit_id
) a
 where a.audit_step = a.node_count and a.total_step > 2';

$result = $con->query($sql);
$datas = [];
while ($row = mysqli_fetch_assoc($result)){
    $datas[] = $row;
}
$result->close();
$con->next_result();
$temp = [];
foreach ($datas as $row){
    $flow_id = $row['id'];
    $step = bcadd($row['audit_step'] , 1);
    $sql2 = 'select * from ba_wf_node where flow_id = '.$flow_id.' and step = '.$step;
    $next_node_result = $con->query($sql2);
    $next_node_row = mysqli_fetch_assoc($next_node_result);
    $next_node_result->close();
    $con->next_result();
    $json = json_decode($next_node_row['scopes'], true);
    $temp[] = [
        "flow_id" => $flow_id,
        "scope_id" => $json[0]['scope_id'],
        "scope_name" => $json[0]['scope_name']
    ];


}
$scopes = [];

foreach ($temp as &$row){
    $sql3 = "select a.group_id,b.id,b.nickname from ba_admin_group_access a 
	left join ba_admin b on a.uid = b.id
	where group_id = '".$row['scope_id']."'";
    $scopes_result = $con->query($sql3);
    $scopes_result_row = mysqli_fetch_assoc($scopes_result);
    $scopes_result->close();
    $con->next_result();
    $row['admin_id'] = $scopes_result_row['id'];
    $row['admin_name'] = $scopes_result_row['nickname'];
}



foreach ($temp as $row){
    $sql4 = 'update ba_wf_workflow set audit_step = audit_step+1, audit_id='.$row['admin_id'].', audit_name="'.$row['admin_name'].'" where id = '.$row['flow_id'];
    printf($sql4);
    $con->query($sql4);
}
$con->close();
//var_dump($temp);